<template>
  <div>
    <div class="upload">
      <el-upload class="avatar-uploader el-upload-list--picture-card" :action="apiUrl"
        :show-file-list="false" :headers="headers" :auto-upload="false" ref="upload"
        :on-change="changeUpload" v-show="!(imageUrl || defaultImgCp)">
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <div class="avatar-uploader el-upload-list--picture-card avatar"
        v-show="imageUrl || defaultImgCp" style="position:relative">
        <!-- 上传到服务器URL地址回显 -->
        <!-- <img :src="imageUrl | filePath(defaultImgCp)" class="avatar" /> -->
        <img :src="imageUrl" class="avatar" />
        <span class="el-upload-list__item-actions" v-if="imageUrl || defaultImgCp">
          <span class="el-upload-list__item-preview">
            <i class="el-icon-zoom-in" @click="handlePictureCardPreview"></i>
          </span>
          <span class="el-upload-list__item-preview upload-btn" v-if="!hideEdit">
            <el-upload :action="apiUrl" :show-file-list="false" :headers="headers"
              :auto-upload="false" ref="upload" :on-change="changeUpload">
              <i class="el-icon-upload"></i>
            </el-upload>
          </span>
          <span class="el-upload-list__item-delete" v-if="!hideDelete">
            <i class="el-icon-delete" @click="handleRemove"></i>
          </span>
        </span>
      </div>
    </div>
    <!-- vueCropper 剪裁图片实现-->
    <el-dialog :title="$t('pictureCropping')" :visible.sync="cropperVisible" width="500px"
      v-if="cropperVisible" :close-on-click-modal="false">
      <div class="cropper-content" style="display: flex;justify-content: center;">
        <div style="width:400px;height:400px">
          <img :src="img" :id="imgCrop">
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cropperVisible = false">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click="cropperFinish">{{$t('ok')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" width="500px">
      <!-- <img width="100%" :src="dialogImageUrl | filePath(defaultImgCp)" alt=""> -->
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>

</template>
<script>
import { environment } from '../../models/environment';
import axios from 'axios';
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css';
export default {
  name: 'ImageCropperUpload',
  props: {
    url: {
      type: String,
      default: '',
    },
    defaultImg: {
      type: String,
      default: '',
    },
    hideDelete: {
      type: Boolean,
      default: false,
    },
    hideEdit: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    // VueCropper
  },
  data() {
    let id = 'image_upload_' + Date.now() + Math.floor(Math.random() * 1000);
    return {
      imageUrl: this.url || '',
      apiUrl: environment.API_URL + '/upload',
      headers: {},
      dialogImageUrl: '',
      dialogVisible: false,
      img: '',
      cropperVisible: false,
      id: id,
      myCropper: null,
      imgCrop: id + '_crop',
      defaultImgCp: this.defaultImg,
    }
  },
  watch: {
    url(val) {
      this.imageUrl = val
    },
    imageUrl(val) {
      this.$emit('update:url', val)
    },
    defaultImg(val) {
      this.defaultImgCp = val;
    }
  },
  computed: {

  },
  mounted() {
  },
  methods: {

    // 上传图片
    changeUpload(file, fileList) {
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(file.raw.name)) {
        this.$message.warning(this.$t('pictureTypeVerifyTip'))
        return false
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.warning(this.$t('uploadPictureFileSizeTip'))
        return false
      }
      // URL.createObjectURL的参数只能是blob或者file类型
      // 第一种方法用FileReader，URL.createObjectURL接收blob类型
      let reader = new FileReader()
      reader.onload = (e) => {
        let data = '';
        // if (e.target && typeof(e.target.result) == 'object') {
        //   // 把Array Buffer转化为blob 如果是base64不需要
        //   data = window.URL.createObjectURL(new Blob([e.target.result]))
        // } else {
        //   data = e.target.result
        // }
        data = window.URL.createObjectURL(new Blob([e.target.result]))
        this.img = data
        this.$nextTick(() => {
          this.myCropper = new Cropper(document.getElementById(this.imgCrop), {
            viewMode: 1,
            initialAspectRatio: 1,
            aspectRatio: 1,
            background: false,
            ready() {

            }
          })
        })
      }
      // 转化为base64
      this.cropperVisible = true
      reader.readAsArrayBuffer(file.raw)

      // //第二种方法，URL.createObjectURL接收file类型
      // this.$nextTick(() => {
      //   this.option.img = URL.createObjectURL(file.raw)
      //   this.cropperVisible = true
      // })
    },

    // 点击剪裁弹框的确定按钮
    cropperFinish() {
      this.cropperByBase64();
    },

    // 转成blob
    blobToFile(Blob, fileName) { // 兼容IE
      Blob.lastModifiedDate = new Date()
      Blob.name = fileName
      return Blob
    },

    /**
     * FormData对象文件流上传
     */
    cropperByFormData() {
      this.myCropper.getCroppedCanvas().toBlob((data) => {
        console.log("this.myCropper.getCroppedCanvas ~ data:", data)
        let form = new FormData()
        let file = this.blobToFile(data, 'filename.jpg')
        form.append('file', form)
        this.cropperVisible = false;
        // 正式调接口
        axios({
          method: 'POST',
          url: this.apiUrl,
          data: form
        }).then((res) => {
          if (res.data && res.data.success) {
            this.imageUrl = res.data.fname;
            this.cropperVisible = false;
          } else {
            this.$message.warning(res.data.message)
          }
        })
      })
    },

    /**
     * base64上传
     */
    cropperByBase64() {
      let base64 = this.myCropper.getCroppedCanvas().toDataURL('image/jpeg');
      this.imageUrl = base64;
      this.cropperVisible = false;
    },
    

    handleRemove(file, fileList) {
      this.imageUrl = '';
      this.defaultImgCp = '';
      this.$emit('update:defaultImg', this.defaultImgCp)
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.imageUrl;
      this.dialogVisible = true;
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.upload-btn {
  .el-upload {
    border: none !important;
    width: 20px;
    height: 23px;

    &:focus {
      color: #fff;
    }
  }
}
</style>
